package com.qf.fiter;

import com.qf.entity.Admin;
import com.qf.util.PropertiesUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Filter010Login implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //强制类型转换  请求和响应
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp =(HttpServletResponse) response;

        //获得拦截的url
        String uri =req.getRequestURI();
        System.out.println("过滤uri"+uri);
        //从session中获取用户登录状态
        Admin admin =(Admin) req.getSession().getAttribute("login_user");
        if (admin !=null|| uri.endsWith("login.jsp") || uri.endsWith("code")){
            filterChain.doFilter(req,resp);
        }else{
            String nologin = PropertiesUtils.getProperties("nologin");
            if (nologin != null){
                String[] res =nologin.split("\\|");
                for (String re:res) {
                    if (uri.endsWith(re)){
                        filterChain.doFilter(req,resp);
                        return;
                    }
                }
            }
            resp.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
